<template>
  <div :style="{background: autoBGCover(aiContractBG)}" class="wrap">
    <scroll-view
      :scroll-top="scrollTop"
      :style="{height: `calc(100vh - ${storeState.bottomSafeDis + 108 + 24 + 18}rpx)`,padding: '20rpx 20rpx 36rpx', background: autoBGCover(contractPreviewBG)}"
      scroll-y
    >
      <textarea
        id="myTextarea"
        v-model="contractContent"
        :adjust-position="true"
        :disabled="isDisabled"
        :style="{width: '100%',minHeight: '100%'}"
        auto-height
        maxlength="-1"
        @linechange="linechangeFn"
      />
    </scroll-view>
    <div :style="keepBottomSafeDis()" class="suction_bottom_btn">
      <Button :disabled="isDisabled" :styles="{marginRight: '36rpx'}" size="N" type="solid" @tap="rewriteFn">重新写</Button>
      <Button :disabled="isDisabled" :styles="{background: autoBGCover(aiContractDownloadBtn)}" size="N" @tap="downLoadFileFn">下载文件</Button>
    </div>
    <!--  重新写  -->
    <Popup ref="rewriteRef">
      <div :style="{background: autoBGCover(aiContractRewriteBG)}" class="ai_popup_cen">
        <div class="popup_title">
          您想怎么改？
          <div class="icon_close" @tap="rewriteRef.change()">
            <Icon name="icon-shanchu-4" size="28" />
          </div>
        </div>
        <div style="padding: 26rpx 26rpx 0;">
          <u--textarea v-model.trim="textareaVal" height="364rpx" placeholder="例如：重新写一份" />
          <div class="flex_cen_cen mt20">
            <Button :disabled="!textareaVal" :styles="{background: autoBGCover(aiGenerateContractBtn), width: '620rpx'}" size="L" @tap="rebuildContractFn">确认</Button>
          </div>
        </div>
      </div>
    </Popup>
    <!--  下载文件  -->
    <Popup ref="downLoadFileRef">
      <div :style="{background: autoBGCover(aiContractRewriteBG)}" class="ai_popup_cen">
        <div class="popup_title popup_title1">
          复制下载链接，粘贴到微信聊天窗口并发送。
          <div class="icon_close" @tap="downLoadFileRef.change()">
            <Icon name="icon-shanchu-4" size="28" />
          </div>
        </div>
        <div style="padding: 26rpx 26rpx 0;">
          <div class="paste_box">
            您生成的{{ params.type }}文件已完成 请在{{ downloadDate }}前下载，文件内容需要经过审核才能使用。
            <div class="base_color">{{ downLoadUrl }}</div>
          </div>
          <div class="flex_cen_cen mt20">
            <Button :styles="{background: autoBGCover(aiGenerateContractBtn), width: '620rpx'}" size="L" @tap="copyUrlFn">复制到粘贴板</Button>
          </div>
        </div>
      </div>
    </Popup>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, computed, getCurrentInstance, nextTick, onUnmounted } from 'vue'
import { abortRequest, autoBGCover, keepBottomSafeDis, onLoad, storeState } from '@U/common'
import Button from '@C/Button.vue'
import Icon from '@C/Icon.vue'
import Popup from '@C/Popup.vue'
import { MsgLoading, MsgLoadingClear } from '@C/Msg'
import dayjs from 'dayjs'
import { downloadAIContract, generateContract, rebuildContract } from './request'

const aiContractBG = computed(() => `${import.meta.env.VITE_SHOUDAO_OSS_URL}/ai/ai_contract_bg.png`)
const aiContractDownloadBtn = computed(() => `${import.meta.env.VITE_SHOUDAO_OSS_URL}/ai/ai_contract_download_btn.png`)
const aiContractRewriteBG = computed(() => `${import.meta.env.VITE_SHOUDAO_OSS_URL}/ai/ai_contract_rewrite_bg.png`)
const aiGenerateContractBtn = computed(() => `${import.meta.env.VITE_SHOUDAO_OSS_URL}/ai/ai_generate_contract_btn.png`)
const contractPreviewBG = computed(() => `${import.meta.env.VITE_SHOUDAO_OSS_URL}/ai/contract_preview_bg.png`)
const contractContent = ref('')
const params = reactive({
  type: '',
  name: '',
  prompt: '',
  changePrompt: '',
  content: '',
})
const instance = getCurrentInstance()// 获取当前组件实例
const query = uni.createSelectorQuery().in(instance)
const scrollTop = ref(0)
const linechangeFn = () => {
    nextTick(() => {
      query.select('#myTextarea').boundingClientRect((res) => {
        if (res?.height) {
          scrollTop.value = res.height
        }
      }).exec()
    })
}
onLoad((option: any) => {
  for (const key in params) {
    params[key] = option[key]
  }
  generateContractFn()
})
const isDisabled = ref(true)
let requestTaskTemp: any
const onChunkReceivedFn = (requestTask: object) => {
  MsgLoadingClear()
  requestTaskTemp = requestTask // 用于中断操作
  requestTask.onChunkReceived((res: object) => {
    const uint8Array = new Uint8Array(res.data)
    let resultString = String.fromCharCode.apply(null, uint8Array)
    // 匹配接口返回的字符串中包含data: [DONE]格式的
    if (!/data:\s*\[DONE]/g.test(resultString)) {
      resultString = decodeURIComponent(escape(resultString))
      const cleanedContent = resultString.replaceAll('data:', ',')
      const splitContent = `[${ cleanedContent.replace(/^,/, '') }]`
      const dataArray = JSON.parse(splitContent)
      dataArray.forEach((item: string) => {
        contractContent.value += JSON.parse(item).Content
      })
    } else {
      isDisabled.value = false
      abortRequest(requestTask)
    }
  })
}
const generateContractFn = async () => {
  await MsgLoading()
  const requestTask = await generateContract(params).finally(() => {})
  onChunkReceivedFn(requestTask)
}

const rewriteRef = ref()
const textareaVal = ref('')
const rewriteFn = () => {
  if (isDisabled.value) return
  rewriteRef.value.change()
}
const rebuildContractFn = async () => {
  if (!textareaVal.value) return
  await MsgLoading()
  params.changePrompt = textareaVal.value
  params.content = contractContent.value
  const requestTask = await rebuildContract(params).finally(() => {})
  // 重置
  textareaVal.value = ''
  contractContent.value = ''
  isDisabled.value = true
  onChunkReceivedFn(requestTask)
  rewriteRef.value.change()
}
const downLoadFileRef = ref()
const downLoadUrl = ref('')
const downloadDate = ref('')
const downLoadFileFn = async () => {
  if (isDisabled.value) return
  downloadDate.value = dayjs().add(3, 'day').format('MM月DD日')
  await MsgLoading()
  const { code, data } = await downloadAIContract({ content: contractContent.value }).finally(() => MsgLoadingClear())
  if (code === 200) {
    downLoadUrl.value = data
    downLoadFileRef.value.change()
  }
}
const copyUrlFn = () => {
  uni.setClipboardData({
    data: downLoadUrl.value,
    success() {
      downLoadFileRef.value.change()
      uni.showToast({
        title: '复制成功',
        icon: 'success',
      })
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'error',
      })
    },
  })
}
onUnmounted(() => {
  // 页面销毁时中断输出
  abortRequest(requestTaskTemp)
})
</script>

<style lang="less" scoped>
.wrap {
  padding: 24rpx;
  .ai_popup_cen {
    width: 670rpx;
    border-radius: 32rpx;
    padding: 28rpx 0 40rpx;
    .popup_title {
      position: relative;
      font-size: 36rpx;
      font-weight: 600;
      color: #2192FF;
      text-align: center;
      line-height: 56rpx;
      border-bottom: 2rpx solid rgba(0,0,0,0.1);
      padding-bottom: 28rpx;
    }
    .popup_title1 {
      font-size: 26rpx;
      text-align: left;
      padding-left: 26rpx;
    }
    .icon_close {
      position: absolute;
      top: 0;
      right: 36rpx;
      width: 50rpx;
      text-align: right;
      opacity: 0.5;
    }
    .paste_box {
      font-size: 26rpx;
      height: 200rpx;
      word-break: break-all;
      padding: 22rpx;
      background: rgba(255,255,255,0.8);
      box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0,0,0,0.1);
      border-radius: 12rpx;
    }
  }
  .output {
    white-space: pre-wrap; /* 保留空白符和换行符 */
  }
}
</style>
